<template>
	<div class="manage" v-if="currentGroup">
		<u-navbar placeholder :title="currentGroup.name" 
			:rightText="isAdmin && isSetMuteTime?'设置管理员':''" @leftClick="back" @rightClick="setCurrentTab('admin')">
		</u-navbar>
		<main class="main">
			<div class="userInfo space-top">
				<ol class="userInfo-list">
					<dl class="userInfo-list-item" v-for="(item, index) in groupMemberList.slice(0, showUserNum)"
						:key="index">
						<dt class="userInfo-list-item-main" @click="handleMemberProfileShow(item)">
							<Avatar useSkeletonAnimation :url="item.avatar" size="100rpx" />
						</dt>
						<dd class="userInfo-list-item-info">{{ item.nick || item.userID }}</dd>
					</dl>
					<dl class="userInfo-list-item" v-if="currentSelfRole === 'Owner'">
						<dt class="avatar avatar-add" @click="toggleMask('add')">+</dt>
						<dd class="userInfo-list-item-info">邀请</dd>
					</dl>
					<dl class="userInfo-list-item" v-if="currentSelfRole === 'Owner'">
						<dt class="avatar avatar-add" @click="toggleMask('remove')">-</dt>
						<dd class="userInfo-list-item-info">移除</dd>
					</dl>
				</ol>
				<div class="view-member" @click="setCurrentTab('member')">
					<span>查看更多群成员</span>
					<Icon :file="rightIcon"></Icon>
				</div>
			</div>

			<ul class="content list space-top" @click="editLableName = ''">
				<li class="list-item">
					<label class="label">{{
				  TUITranslateService.t(`TUIGroup.群头像`)
				}}</label>
					<img class="avatar" :src="
				    currentGroup.avatar ||
				    'https://main-pro.yanchaochao.com/mp-static/96x96.png'
				  " onerror="this.onerror=null;this.src='https://main-pro.yanchaochao.com/mp-static/96x96.png'" />
				</li>
				<li class="list-item" @click="setCurrentTab('name')">
					<aside class="aside">
						<label class="label">{{
				  TUITranslateService.t(`TUIGroup.群聊名称`)
				}}</label>
						<article class="article">{{currentGroup.name}}</article>
					</aside>
					<Icon :file="rightIcon" class="end"></Icon>
				</li>
				<li class="list-item" @click="setCurrentTab('notification')">
					<aside class="aside">
						<label class="label">{{
              TUITranslateService.t(`TUIGroup.群公告`)
            }}</label>
						<article class="article">{{ notification.notificationText }}</article>
					</aside>
					<Icon :file="rightIcon" class="end"></Icon>
				</li>
			</ul>
			<ul class="footer list space-top">
				<li class="list-item" v-if="canIDissmissGroup" @click.stop="toggleMask('dismiss')">
					{{ TUITranslateService.t(`TUIGroup.解散群聊`) }}
				</li>
				<li class="list-item" v-else @click.stop="toggleMask('quit')">
					{{ TUITranslateService.t(`TUIGroup.退出群组`) }}
				</li>
			</ul>
		</main>
		<!-- 退出或者解散群聊弹窗 -->
		<Dialog class="deleted-dialog" :title="transferTitle.value" :show="delDialogShow"
			:isH5="!isPC" :center="true" :isHeaderShow="isPC" @submit="transferType==='dismiss'?dismissGroup(currentGroup):quitGroup(currentGroup)"
			@update:show="(e) => (delDialogShow = e)">
			<p>确认{{transferTitle}}?</p>
		</Dialog>
		<ManageAdmin v-if="currentTab === 'admin'" v-show="isAdmin" :isSetMuteTime="isSetMuteTime" :member="member"
			:currentGroup="currentGroup" @addAdmin="toggleMask('addAdmin')" @removeAdmin="toggleMask('removeAdmin')"
			@setAllMuteTime="setAllMuteTime" @addMute="toggleMask('addMute')" @removeMute="toggleMask('removeMute')"
			@close="setCurrentTab('')" />
		<MaskLayer :show="mask" @update:show="(e) => (mask = e)">
			<SelectUser :isRadio="isRadio" :isNeedSearch="true"
				:title="TUITranslateService.t(`TUIGroup.${transferTitle}`)" :userList="transferList"
				@search="handleSearchMember" @complete="submit" />
		</MaskLayer>

	</div>
</template>
<script lang="ts" setup>
	import {
		ref,
		computed,
		watchEffect,
	} from "../../../adapter-vue";
	import { onLoad,onShow } from "@dcloudio/uni-app";
	import TUIChatEngine, {
		TUITranslateService,
		TUIGroupService,
		TUIConversationService,
		TUIStore,
		StoreName,
		IGroupModel,
	} from "@tencentcloud/chat-uikit-engine";
	import { IGroupMember } from "../../../interface";
	import { TUIGlobal } from "@tencentcloud/universal-api";
	import MaskLayer from "../../common/MaskLayer/index.vue";
	import Dialog from "../../common/Dialog/index.vue";
	import SelectUser from "../../common/SelectUser/index.vue";
	import ManageAdmin from "./manage-admin.vue";
	import Icon from "../../common/Icon.vue";
	import rightIcon from "../../../assets/icon/right-icon.svg";
	import { Toast, TOAST_TYPE } from "../../common/Toast/index";
	import { isPC, isUniFrameWork } from "../../../utils/env";
	import Avatar from "../../common/Avatar/index.vue";
	import { enableSampleTaskStatus } from "../../../utils/enableSampleTaskStatus";
	import { checkUserInfo } from "../../../utils/checkLogin";

	const currentTab = ref("");
	const editLableName = ref("");
	const transferType = ref("");
	const mask = ref(false);
	// 群公告信息
	const notification = ref<any>({
		notificationText: '',
		notificationOpt: {
			date: '',
			name: ''
		}
	});
	const currentMember = ref<IGroupMember>({});
	const member = ref({
		admin: [] as Array<IGroupMember>,
		member: [] as Array<IGroupMember>,
		muteMember: [] as Array<IGroupMember>,
	});
	const transferList = ref<Array<IGroupMember>>([]);
	const transferTitle = ref("");
	const isRadio = ref(false);
	const selectedList = ref([]);
	const delDialogShow = ref(false);
	const groupMemberList = ref<Array<IGroupMember>>([]);
	const deletedUserList = ref([]);
	const currentGroup = ref<IGroupModel>();
	const currentSelfRole = ref("");
	const groupID = ref("");
	//获取当前群聊信息
	TUIStore.watch(StoreName.GRP, {
		currentGroup: (group : IGroupModel) => {
			if (group) {
				currentGroup.value = group;
				currentSelfRole.value = currentGroup.value?.selfInfo?.role;
				if (!!group.notification) {
					let notificationInfo = group.notification.split('&notificationOpt=')
					notification.value = {
						notificationText: notificationInfo[0],
						notificationOpt: JSON.parse(notificationInfo[1])
					}
				}
			}
		},
		currentGroupMemberList: (memberList : Array<typeof IGroupMember>) => {
			groupMemberList.value = memberList;
			member.value = {
				admin: [],
				member: [],
				muteMember: [],
			};
			Array.from(memberList).map((item : any) => {
				switch (item?.role) {
					case TUIChatEngine.TYPES.GRP_MBR_ROLE_ADMIN:
						member.value.admin.push(item);
						break;
					case TUIChatEngine.TYPES.GRP_MBR_ROLE_MEMBER:
						member.value.member.push(item);
						break;
					default:
						break;
				}
				return item;
			});
			const time : number = new Date().getTime();
			member.value.muteMember = Array.from(memberList).filter(
				(item : any) => item?.muteUntil * 1000 - time > 0
			);
		},
	});


	onLoad((options : any) => {
		groupID.value = options.groupID
		TUIStore.watch(StoreName.CUSTOM, {
			IMuserInfo: (data) => {
				if (data) {
					//H5刷新
					TUIGroupService.switchGroup(options.groupID);
				}

			}
		})
	})
	onShow(() => {
		//已经登录之后
		TUIStore.watch(StoreName.CUSTOM, {
			IMuserInfo: (data) => {
				if (data) {
					checkUserInfo()
				}
			}
		})
	})

	const isAuthor = computed(() => {
		// 判断是否是群主/管理员
		const userRole = currentGroup?.value?.selfInfo?.role;

		const isOwner = userRole === TUIChatEngine.TYPES.GRP_MBR_ROLE_OWNER;
		const isAdmin = userRole === TUIChatEngine.TYPES.GRP_MBR_ROLE_ADMIN;
		return isOwner || isAdmin;
	});

	const isAdmin = computed(() => {
		const groupType = currentGroup?.value?.type;
		const userRole = currentGroup?.value?.selfInfo?.role;

		const isOwner = userRole === TUIChatEngine.TYPES.GRP_MBR_ROLE_OWNER;
		const isWork = groupType === TUIChatEngine.TYPES.GRP_WORK;
		const isAVChatRoom = groupType === TUIChatEngine.TYPES.GRP_AVCHATROOM;

		if (!isWork && !isAVChatRoom && isOwner) {
			return true;
		}
		return false;
	});

	const isSetMuteTime = computed(() => {
		const groupType = currentGroup?.value?.type;
		const isWork = groupType === TUIChatEngine.TYPES.GRP_WORK;

		if (isWork || !isAuthor.value) {
			return false;
		}
		return true;
	});

    //修改群资料
	const updateProfile = async (newGroupProfile : any) => {
		const { key, value } = newGroupProfile;
		const options : any = {
			groupID: currentGroup.value.groupID,
			[key]: value,
		};
		TUIGroupService.updateGroupProfile(options)
			.then((res : any) => {
				currentGroup.value = res.data.group;
				editLableName.value = "";
			})
			.catch((error : any) => {
				Toast({
					message: error?.message,
					type: TOAST_TYPE.ERROR,
				});
			});
	};
	//修改群信息事件跳转
	const setCurrentTab = (tabName : string) => {
		//修改群公告
		if (tabName === "notification") {
			TUIGlobal?.navigateTo({
				url: "/pages/TUIKit/components/TUIGroup/manage-group/manage-notification?groupID=" + groupID.value + '&isAuthor=' + isAuthor.value,
			});
			return
		}
		//修改群名称
		if (tabName === "name") {
			TUIGlobal?.navigateTo({
				url: "/pages/TUIKit/components/TUIGroup/manage-group/manage-name?groupID=" + groupID.value + '&isAuthor=' + isAuthor.value,
			});
			return
		}
		//群成员列表
		if (tabName === "member") {
			// 管理群成员
			TUIGlobal?.navigateTo({
				url: "/pages/TUIKit/components/TUIGroup/manage-group/manage-member?groupID=" + groupID.value
			});
			return
		}
		//设置管理员
		if (tabName === "admin") {
			// 管理群成员
			TUIGlobal?.navigateTo({
				url: "/pages/TUIKit/components/TUIGroup/manage-group/manage-admin?groupID=" + groupID.value
			});
			return
		}

	};
    //操作群成员事件
	const toggleMask = async (type ?: string) => {
		type && (transferType.value = type);
		if(type==='dismiss'){
			transferTitle.value = "解散群聊";
			delDialogShow.value=true;
			return;
		}
		if(type==='quit'){
			transferTitle.value = "退出群聊";
			delDialogShow.value=true;
			return;
		}
		switch (type) {
			case "add":
				transferTitle.value = "添加成员";
				break;
			case "remove":
				transferTitle.value = "删除成员";
				break;
			case "addAdmin":
				isRadio.value = true;
				transferList.value = member.value.member;
				transferTitle.value = "新增管理员";
				break;
			case "removeAdmin":
				isRadio.value = true;
				transferList.value = member.value.admin;
				transferTitle.value = "移除管理员";
				break;
			default:
				break;
		}
		
		TUIGlobal?.navigateTo({
			url: '/pages/TUIKit/components/TUIGroup/manage-group/manage-userList?title=' + transferTitle.value + '&GroupID=' + groupID.value + '&type=' + type
		})

	};
	const dismissGroup = async (group : any) => {
		console.log(TUIChatEngine,"TUIChatEngine")
		// 解散群组
		await TUIGroupService.dismissGroup(group.groupID);
		Toast({
			message: TUITranslateService.t("TUIGroup.群组解散成功"),
			type: TOAST_TYPE.SUCCESS,
		});
		clearGroupInfo();
	};
	//退出群聊
	const quitGroup = async (group : any) => {
		await TUIGroupService.quitGroup(group.groupID);
		clearGroupInfo();
	};
	
	//清除群信息
	const clearGroupInfo = () => {
		//删除会话并清空历史消息
		TUIChatEngine.chat.deleteConversation({conversationIDList: ['GROUP'+groupID.value], clearHistoryMessage: false}).then(res=>{
			TUIGlobal?.redirectTo({
				url: "/pages/TUIKit/components/TUIGroup/index",
			});
		})
		

		
	};

	//是否可以解散群聊 权限判断
	const canIDissmissGroup = computed(() => {
		const userRole = currentGroup?.value?.selfInfo?.role;
		const groupType = currentGroup?.value?.type;

		return (
			userRole === TUIChatEngine.TYPES.GRP_MBR_ROLE_OWNER &&
			groupType !== TUIChatEngine.TYPES.GRP_WORK
		);
	});
    //是否拥有邀请群成员权限
	const isShowAddMember = computed(() => {
		const groupType = currentGroup?.value?.type;
		return groupType === TUIChatEngine.TYPES.GRP_WORK;
	});
	//管理页面显示多少群成员
	const showUserNum = computed(() => {
		let num = 13;
		if (currentGroup?.value?.selfInfo?.role !== "Owner") {
			num += 1;
		}
		if (!isShowAddMember.value) {
			num += 1;
		}
		return num;
	});

	//显示资料
	const handleMemberProfileShow = (user : any) => {
		currentMember.value = user;
		setCurrentTab("profile");
	};

	const submit = (userList : any) => {
		// 进行成员移除等等相关操作
		if (transferType.value === "remove") {
			deletedUserList.value = userList;
			delDialogShow.value = !delDialogShow.value;
		} else {
			handleManage(userList, transferType.value);
		}
		mask.value = false;
	};



	//更改管理员
	const changeOwner = async (userID : any) => {
		const options : any = {
			groupID: currentGroupID.value,
			newOwnerID: userID,
		};
		const imResponse = await TUIGroupService.changeGroupOwner(options);
		currentGroup.value = {};
		currentGroup.value = imResponse.data.group;
	};
   
	const back = () => {
		uni.navigateBack()
	};

</script>
<style lang="scss" scoped src="./style/index.scss"></style>
<style lang="scss">
	::v-deep .u-navbar__content__right__text,
	::v-deep .uicon-account {
		color: #FA3121 !important;
		font-weight: bold;
	}

	.view-member {
		display: flex;
		justify-content: center;
		padding-bottom: 30rpx;
		color: #999;
	}
	.userInfo-list-item:nth-child(5n){
		padding-right: 0 !important;
	}
	.userInfo-list-item{
		padding-bottom:16rpx;
		>.avatar{
			width: 100rpx !important;
			height: 100rpx !important;
		}
		
	}
</style>